package fnsvr

import (
	"fmt"
	"runtime/debug"
	"strconv"

	"github.com/nats-io/nats.go"
)

type NatsConn struct {
	conn *nats.Conn
}

// 创建nats连接
func CreateNatsConn(cfg *NatsConfig) (*NatsConn, error) {

	url := "nats://" + cfg.Host + ":" + strconv.Itoa(cfg.Port)
	fmt.Printf("nats url: %s\n", url)
	natsConn, err := nats.Connect(url)
	if err != nil {
		return nil, err
	}

	return &NatsConn{conn: natsConn}, nil
}

func (nc *NatsConn) Subscribe(subscribeAddr string, handler func(msg *nats.Msg)) {
	nc.conn.Subscribe(subscribeAddr, func(msg *nats.Msg) {
		defer func() {
			if r := recover(); r != nil {
				errMsg := fmt.Sprintf("natsSubscribe subscribeAddr:%s recovered from panic: %v, stack: %s", subscribeAddr, r, debug.Stack())
				Log().Error(errMsg)
			}
		}()
		handler(msg)
	})
}

func (nc *NatsConn) Close() {
	if nc.conn != nil {
		nc.conn.Close()
	}
}

func (nc *NatsConn) Publish(subject string, msg []byte) error {
	return nc.conn.Publish(subject, msg)
}
